import joblib
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel

from dbutils import DbHelper
import jieba
db = DbHelper()
def myfit():
    words=[]
    # 获取内容简介
    lines=db.query("select descs from books")
    for line in lines:
        cuts=jieba.lcut(line[0])
        words.append(" ".join(cuts))
    tfidf=TfidfVectorizer()
    matrix=tfidf.fit_transform(words)
    # 余弦矩阵
    cos=linear_kernel(matrix)
    # 保存模型
    with open("recs.pkl","wb") as f:
        joblib.dump(cos,f)
def run(id):
    with open("recs.pkl","rb") as f:
        model=joblib.load(f)
    # 第一本书
    first=model[id-1]
    b=list(enumerate(first))
    b.sort(key=lambda x:x[1],reverse=True)
    # 醉相思的前5本书
    top5=b[1:6]
    print(top5)
    top5=tuple(map(lambda x:x[0]+1,top5))
    last=db.query(f"select title,coverpic from books where id in {top5}")
    print(last)
    return last
if __name__ == '__main__':
    # myfit()
    run()

